package ru.space_game.entities;

import ru.space_game.core.Game;

/**
 * An entity representing a shot fired by the player's ship
 * 
 * @author Kevin Glass
 * @author Brian Matzon
 */
public class ShotEntity extends Entity {

	private static final int MAX_RANGE = 500;

	/** True if this shot has been "used", i.e. its hit something */
	private boolean used;

	private int rangeRemains = MAX_RANGE;

	/**
	 * Create a new shot from the player
	 * 
	 * @param game
	 *            The game in which the shot has been created
	 * @param sprite
	 *            The sprite representing this shot
	 * @param x
	 *            The initial x location of the shot
	 * @param y
	 *            The initial y location of the shot
	 */
	public ShotEntity(Game game, String sprite, int x, int y) {
		super(game.getSprite(sprite), x, y);
		speed = 500;
	}

	/**
	 * Reinitializes this entity, for reuse
	 * 
	 * @param x
	 *            new x coordinate
	 * @param y
	 *            new y coordinate
	 */
	public void reinitialize(int x, int y) {
		Entity ship = Game.getInstance().getWorld().getShip();
		angel = ship.getAngel();
		this.x = x - (int) (Math.sin(angel * Math.PI / 180) * (ship.getSize() * Math.sqrt(2)));
		this.y = y - (int) (Math.cos(angel * Math.PI / 180) * (ship.getSize() * Math.sqrt(2)));
		used = false;
		rangeRemains = MAX_RANGE;
		visible = false;
	}

	/**
	 * Request that this shot moved based on time elapsed
	 * 
	 * @param delta
	 *            The time that has elapsed since last move
	 */
	public void move(long delta) {
		// proceed with normal move
		x -= delta * speed * Math.sin(angel * Math.PI / 180) / 1000;
		y -= delta * speed * Math.cos(angel * Math.PI / 180) / 1000;

		rangeRemains -= speed * (delta / 1000f);

		// if we shot off the screen, remove ourself
		if (rangeRemains < 0) {
			Game.getInstance().getWorld().removeEntity(this);
		}
	}

	/**
	 * Notification that this shot has collided with another entity
	 * 
	 * @param other
	 *            The other entity with which we've collided
	 */
	public void collidedWith(Entity other) {
		// prevents double kills, if we've already hit something,
		// don't collide
		if (used) {
			return;
		}

		// if we've hit an alien, kill it!
		if (other instanceof AlienEntity) {
			// remove the affected entities
			Game.getInstance().getWorld().removeEntity(this);
			Game.getInstance().getWorld().removeEntity(other);

			// notify the game that the alien has been killed
			Game.getInstance().getWorld().notifyAlienKilled();
			used = true;
		}
	}
}